package com.cqw.aspect;

import com.alibaba.fastjson.JSON;
import com.cqw.annotation.Log;
import com.cqw.domain.SysLog;
import com.cqw.enums.BusinessStatusEnum;
import com.cqw.mq.MqProvider;
import com.cqw.utils.IpUtils;
import com.cqw.utils.ServletUtils;
import com.cqw.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-05-08 14:30
 * @Description:
 */
@Aspect
@Slf4j
public class LogAspect {


    @Resource
    private MqProvider mqProvider;


    //声明切面注解
    public static final String POINTCUT = "@annotation(com.cqw.annotation.Log)";


//    @Before(POINTCUT)
//    public void beforeAop(JoinPoint joinPoint) {
//        System.out.println("前置通知");
//    }
//
//    @After(POINTCUT)
//    public void afterAop() {
//        System.out.println("后置通知");
//    }


    @AfterReturning(pointcut = POINTCUT, returning = "jsonObject")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonObject) {
        handleLog(joinPoint, null, jsonObject);
    }


    private void handleLog(JoinPoint joinPoint, Exception e, Object jsonObject) {
        //获得注解
        Log annotationLog = getAnnotationLog(joinPoint);
        if (annotationLog == null) {
            return;
        }

        //获取当前用户

        //操作数据库
        SysLog sysLog = new SysLog();
        sysLog.setStatus(BusinessStatusEnum.SUCCESS.getCode());
        //请求的地址
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        sysLog.setOperIp(ip);
        //返回参数
        sysLog.setJsonResult(JSON.toJSONString(jsonObject));
        //请求URL
        sysLog.setOperUrl(ServletUtils.getRequest().getRequestURL().toString());

        if (e != null) {
            sysLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            sysLog.setStatus(BusinessStatusEnum.FAIL.getCode());
        }

        //方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //设置请求方式
        sysLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        //处理设置注解上的参数
        getControllerMethodDescription(joinPoint, annotationLog, sysLog);
        //保存到数据库
        mqProvider.sendLog(JSON.toJSONString(sysLog));
    }


    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint
     * @param annotationLog
     * @param sysLog
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, Log annotationLog, SysLog sysLog) {
        //设置标题
        sysLog.setTitle(annotationLog.title());
        //设置业务类型
        sysLog.setBusinessType(annotationLog.businessType().ordinal());
        //设置操作人类别
        sysLog.setOperatorType(annotationLog.operatorType().ordinal());
        //是否需要保存request的参数和值
        if (annotationLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, sysLog);
        }

    }

    private void setRequestValue(JoinPoint joinPoint, SysLog sysLog) {
        String requestMethod = sysLog.getRequestMethod();
        if ("PUT".equalsIgnoreCase(requestMethod) || "POST".equalsIgnoreCase(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            sysLog.setOperParam(StringUtils.substring(params.toString(), 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            sysLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }


    /**
     * 参数拼接
     *
     * @param paramsArray
     * @return
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";

        if (paramsArray != null && paramsArray.length > 0) {
            for (Object param : paramsArray) {
                if (!isFilterObject(param)) {
                    Object json = JSON.toJSON(param);
                    params += json.toString() + " ";
                }
            }
        }
        return params.trim();
    }


    /**
     * 判断是否是需要过滤的对象
     *
     * @param param
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    private boolean isFilterObject(Object param) {
        return param instanceof MultipartFile || param instanceof HttpServletRequest || param instanceof HttpServletResponse;
    }


    /**
     * 获得注解
     *
     * @param joinPoint
     * @return
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method != null) {
                return method.getAnnotation(Log.class);
            }
        }
        return null;
    }


   /* @Around(POINTCUT)
    public void aroundAop(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("***********记录日志开始了**************");
        Signature signature = joinPoint.getSignature();
        CodeSignature codeSignature = (CodeSignature) signature;
        if (signature instanceof MethodSignature) { //判断当前签名是不是方法签名
            MethodSignature methodSignature = (MethodSignature) signature;
            //获取方法
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(Log.class)) {    //判断当前方法是否有Log注解
                Log logAnnotation = method.getAnnotation(Log.class);
                String value = logAnnotation.title();
                //处理参数
                Map<String, Object> param = getNameAndValue(codeSignature, joinPoint);
                log.info("参数：{}", JSON.toJSONString(param));
            }
        }
        joinPoint.proceed();
        log.info("***********记录日志结束了**************");
    }

    private Map<String, Object> getNameAndValue(CodeSignature codeSignature, ProceedingJoinPoint joinPoint) {
        HashMap<String, Object> map = new HashMap<>();
        Object[] paramValues = joinPoint.getArgs();
        String[] paramNames = codeSignature.getParameterNames();
        for (int i = 0; i < paramNames.length; i++) {
            map.put(paramNames[i], paramValues[i]);
        }
        return map;
    }*/


}
